import React, { PureComponent } from "react";
import {
  Input, Form,
} from 'antd';

const FormItem = Form.Item;
const EditableContext = React.createContext();
@Form.create()
class EditableCell extends PureComponent {
  state = {
    editing: false,
  }

  toggleEdit = () => {
    const { editing}=this.state;
    this.setState({ editing: !editing }, () => {
      if (!editing) {
        this.input.focus();
      }
    });
  }

  save = () => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  }

  cellItem = (node) => {
    this.cell = node
  }

  inputItem = (node)=>{
    this.input = node
  }

  render() {
    const { editing } = this.state;
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      form,
      ...restProps
    } = this.props;
    return (
      <td ref={this.cellItem} {...restProps}>
        {editable ? (
          <EditableContext.Consumer>
            {() => {
              this.form = form;
              return (
                editing ? (
                  <FormItem style={{ margin: 0 }}>
                    {form.getFieldDecorator(dataIndex, {
                      rules: [{
                        required: true,
                        message: `请输入${title}`,
                      }],
                      initialValue: record[dataIndex],
                    })(
                      <Input
                        maxLength={32}
                        ref={this.inputItem}
                        onPressEnter={this.save}
                        onBlur={this.save}
                        style={{ width: '100%' }}
                      />
                    )}
                  </FormItem>
                  ) : (
                    <div
                      className="editable-cell-value-wrap"
                      style={{ paddingRight: 24 }}
                      onClick={this.toggleEdit}
                    >
                      {restProps.children}
                    </div>
                  )
              );
            }}
          </EditableContext.Consumer>
        ) : restProps.children}
      </td>
    );
  }
}

export default EditableCell;